home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15608 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  80 lines

  1. Path: news.pi.net!news
  2. From: guyver@pi.net (M.L.A. Lammerse)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: passing 2D arrays to functions
  5. Date: Sat, 20 Apr 1996 08:25:31 GMT
  6. Organization: Planet Internet
  7. Message-ID: <4la7g9$6bg@neptunus.pi.net>
  8. References: <4l58sk$l6r@harbinger.cc.monash.edu.au>
  9. NNTP-Posting-Host: asd21.pi.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. pdrod1@mdw084.cc.monash.edu.au (Mr Paul Rodger) wrote:
  13.  
  14. >Greets - 
  15.  
  16. >I need to pass a 2-dimensional array to a function. Obviously I just want
  17. >to pass a pointer to the first element, and in the past when I wanted to 
  18. >pass a one-dimensional array to a function I did the following which should 
  19. >work fine:
  20.  
  21.  
  22. Well, the way I do it is like this:
  23.  
  24. Here is an example function that requires a 2D-array of integers ( m
  25. rows times n columns), it sum all the elements in it and returns that
  26. value:
  27.  
  28. long Sum (int **Array, int MaxRows, int MaxColumns)
  29.  {
  30.   int i,j;
  31.   long sum=0;
  32.  
  33.     for (j=0;j<MaxRows;j++)
  34.            for (i=0;i<MaxColumns;i++)
  35.             sum += Array[j][i];
  36.   return sum; 
  37. }
  38.  
  39. And now to define the array, you'll create an array of pointers to an
  40. array of integers:
  41.  
  42. #include <stdio.h>
  43.  
  44. main()
  45. {  
  46.   int a1 = {1,2,3};
  47.   int a2 = {4,5,6};
  48.   int a3 = {7,8,9};
  49.  
  50.   int *A = { a1,
  51.        a2,
  52.        a3};
  53.  
  54.  printf ("Sum of elements : %ld \n",sum(A,3,3)); 
  55.  
  56. }
  57.  
  58. I don't know an easier way to do it (please let me know if you do).
  59.  
  60. Another example of 2D-arrays as parameters is the program parameters
  61. in:
  62.  
  63. void main(int argc, char *argv[])
  64.  
  65. I don't remember under which condition you can use 'type *variable[]'
  66. , but it is possible.
  67.  
  68. I hope this helps,
  69.  
  70. Marcel
  71.  
  72.  
  73.  
  74. ***************************************************************
  75. * M.L.A. Lammerse                   | e-mail: guyver@pi.net   *
  76. * Electrical engineering student    | phone : (31)0223-612763 *
  77. * at Alkmaar polytechnic in Holland |                         *
  78. ***************************************************************        
  79.  
  80.